
class TypeMessage {
  static const int login = 0;
  static const int signal = 1;
  static const int text = 2;
  static const int user = 3;

  // 心跳消息
  static const int heartbeat = 4;
}

class User {
  String name;
  String key;

  User({ this.name = "",  this.key =""});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'],
      key: json['key'],
    );
  }
}

abstract class Message{


  int msgType;

  Message(this.msgType);

  Map<String, dynamic> toJson();
}

class SignalMessage extends Message {
  String client;
  String type;
  dynamic data;

  SignalMessage({required this.client, required this.type, required this.data})
      : super(TypeMessage.signal);

  factory SignalMessage.fromJson(Map<String,dynamic> message){
    return SignalMessage(client: message["client"], type: message["type"], data: message["data"]);
  }

  @override
  Map<String, dynamic> toJson() {
    return {
      'msgtype': msgType,
      'client': client,
      'type': type,
      'data': data,
    };
  }
}

class LoginMessage extends Message {
  String name;
  String key;

  LoginMessage({required this.name,required this.key}) : super(TypeMessage.login);

  @override
  Map<String, dynamic> toJson() {
    return {
      'msgtype': msgType,
      'name': name,
      'key':key
    };
  }
}

class TextMessage extends Message {
  String data;

  TextMessage({required this.data}) : super(TypeMessage.text);

  @override
  Map<String, dynamic> toJson() {
    return {
      'msgtype': msgType,
      'data': data,
    };
  }
}

class UserMessage extends Message {
  List<User> data;

  UserMessage({required this.data}) : super(TypeMessage.user);

  @override
  Map<String, dynamic> toJson() {
    return {
      'msgtype': msgType,
      'data': data,
    };
  }

  factory UserMessage.fromJson(List<dynamic> jsonList) {
    List<User> users = jsonList.map((json) => User.fromJson(json)).toList();
    return UserMessage(data: users);
  }

}

// 心跳消息类型
class HeartbeatType{
  static const String ping = "ping";
  static const String pong = "pong";
}

class HeartbeatMessage extends Message{
  String type;
  HeartbeatMessage(this.type) : super(TypeMessage.heartbeat);

  @override
  Map<String, dynamic> toJson() {
    return {
      'msgtype': msgType,
      'type': type,
    };
  }

}
